﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Net.Http.Headers;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.Web.Controllers
{
    public class BaseController : AreasController
    {
        protected internal Sysconfig config;
        protected internal Userconfig uconfig;
        public IWebHostEnvironment _env { get; set; }
        public ActionExecutingContext _context { get; set; }
        public IUsersService _users { get; set; }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            this._context = context;
            config = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            uconfig = Common.XMLConfig.Userconfig.loadConfig(_env.ContentRootPath);
            ViewData["config"] = config;
            ViewData["uconfig"] = uconfig;
            base.OnActionExecuting(context);
            //是否关闭网站
            if (config.webstatus == 0)
            {
                context.Result = Redirect("/Home/Error?msg=" + Utils.UrlEncode(config.webclosereason));
                return;
            }
            ViewBag.BasePage = this;
        }
        #region 页面通用方法==========================================
        /// <summary>
        /// /Web/Error/Index?msg=
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public RedirectResult ToError(string msg)
        {
            return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode(msg));
        }
        #endregion

        #region 会员用户方法==========================================
        /// <summary>
        /// 判断用户是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsUserLogin()
        {
            //如果Session为Null
            if (Request.HttpContext.Session.Get(CMSKeys.SESSION_USER_INFO) != null)
            {
                Users model = ByteConvertHelper.Bytes2Object<Users>(Request.HttpContext.Session.Get(CMSKeys.SESSION_USER_INFO));
                if (model != null)
                {
                    //为了能查询到最新的用户信息，必须查询最新的用户资料
                    var tmodel = _users.GetModel(model.id);
                    if (tmodel == null)
                        return false;
                }
                return true;
            }
            else
            {
                //检查Cookies
                string username = HttpContext.Request.Cookies[CMSKeys.COOKIE_USER_NAME_REMEMBER];
                string password = HttpContext.Request.Cookies[CMSKeys.COOKIE_USER_PWD_REMEMBER];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    Users model = _users.GetModel(username, password, 0, 0, false);
                    if (model != null)
                    {
                        HttpContext.Session.Set(CMSKeys.SESSION_USER_INFO, ByteConvertHelper.Object2Bytes(model));
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 取得用户信息
        /// </summary>
        public Users GetUserInfo()
        {
            if (IsUserLogin())
            {
                Users model = ByteConvertHelper.Bytes2Object<Users>(Request.HttpContext.Session.Get(CMSKeys.SESSION_USER_INFO));
                if (model != null)
                {
                    //为了能查询到最新的用户信息，必须查询最新的用户资料
                    model = _users.GetModel(model.id);
                    return model;
                }
            }
            return null;
        }
        #endregion

        #region 新增方法
        /// <summary>
        /// 判断是否为移动设备
        /// </summary>
        /// <returns></returns>
        public bool IsMobile()
        {
            bool flag = false;
            string agent = this._context.HttpContext.Request.Headers[HeaderNames.UserAgent].ToString();
            string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser", "Mobile" };
            // 排除window桌面系统和苹果桌面系统
            if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
            {
                flag = Array.Find(keywords, delegate (string s) { return agent.Contains(s); }) != null;
            }
            return flag;
        }

        public string GetTimeSpan(DateTime dateTime)
        {
            string result = string.Empty;
            TimeSpan span = DateTime.Now.Subtract(dateTime);
            double dayDiff = span.TotalDays;
            if (dayDiff < 1)
            {
                result = Math.Floor(span.TotalHours).ToString() + "小时前";
            }
            else if (dayDiff <= 31)
            {
                result = Math.Floor(dayDiff).ToString() + "天前";
            }
            else if (dayDiff <= 365)
            {
                result = Math.Floor(dayDiff / 31).ToString() + "月前";
            }
            else
            {
                result = "1年前";
            }
            return result;
        }
        #endregion
    }
}